<?php
namespace serv\task\warehouse;

use L;
use of\base\com\mq;
use Sdk\Plglobal\callPlglobalApiUtil;

//use of_base_com_kv;

class plglobal
{
    //每小时自动同步获取一次token
    public static function token()
    {
        $auth = callPlglobalApiUtil::callPlglobalApi('/3plapi/getToken', 'post', []);
        if (isset($auth['code'])) {
            if (200 == $auth['code']) {
                //把获取到的token数据写到 redis
                $oauth = [
                    'token' => $auth['token'],
                    'expire' => date('Y-m-d H:i:s', time() + 7200)
                ];
                $json = json_encode($oauth);
                //检查是否存在了，存在则更新，否则新增
                $sql = "SELECT id FROM token WHERE 1 AND `type` = 'plglobal';";
                $rows = L::sql($sql);
                if (empty($rows)) {
                    $sql = "INSERT INTO token(`type`, `data`) VALUES ('plglobal', '{$json}');";
                    L::sql($sql);
                } else {
                    $sql = "UPDATE token SET `data` = '{$json}' WHERE 1 AND id = '{$rows[0]['id']}';";
                    L::sql($sql);
                }
                //of_base_com_kv::link('default')->set('plglobal', json_encode($oauth));
            }
        }
    }

    //抓取并同步大健云仓的库存
    public static function pull()
    {
        $sql = "SELECT warehouse_id, warehouse_code FROM warehouse WHERE 1 AND `type` = 110 AND `status` = 1";
        $result = L::sql($sql, 'warehouse');
        if (!empty($result)) {
            //因大健云仓不支付按仓库同步库存，一次就返回所有的，所以只需要一个仓库来同步就可以了
            $warehouseArr = [];
            foreach ($result as $k => $v) {
                $warehouseArr[$v['warehouse_code']] = $v['warehouse_id'];
            }
            foreach ($result as $k => $v) {
                if ('CA2' == $v['warehouse_code']) {
                    $key = "syncPlglogalStock_{$v['warehouse_id']}";
                    $v['warehouse'] = $warehouseArr;
                    //echo json_encode($v); exit;
                    mq::set(["syncPlglogalStock", $key, $k * 10], $v);
                    break;
                }
            }
        }
    }




}